package com.service.purchase;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.ColumnsModel;
import com.common.easyui.GridData;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.ActionEnum;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.InquiryMapper;
import com.dao.purchase.InquiryResultMapper;
import com.dao.purchase.SupplyCompeteDao;
import com.dao.purchase.SupplyCompeteRecordDao;
import com.dao.purchase.SupplyCompeteRecordMmDao;
import com.dao.purchase.SupplyOfferMapper;
import com.dao.purchase.SupplyOfferMmMapper;
import com.dao.sys.LogDao;
import com.model.purchase.PurchaseInquiry;
import com.model.purchase.PurchaseInquiryResult;
import com.model.purchase.PurchaseInquiryVO;
import com.model.purchase.PurchaseSupplyOffer;
import com.model.purchase.PurchaseSupplyOfferMm;
import com.model.purchase.SupplyCompeteMmModel;
import com.model.purchase.SupplyCompeteModel;
import com.model.purchase.SupplyCompeteRecordMmModel;
import com.model.purchase.SupplyCompeteRecordModel;
import com.model.sys.LogModel;
import com.model.sys.SysUser;

/**
 * 报价揭示
 * 
 * @author chenjun
 *
 */
@Service
public class RevealService {

	static final Logger logger = LoggerFactory.getLogger(RevealService.class);

	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	SupplyOfferMapper supplyOfferMapper;
	@Autowired
	SupplyOfferMmMapper supplyOfferMmMapper;

	@Autowired
	InquiryResultMapper inquiryResultMapper;
	@Autowired
	SupplyCompeteRecordDao competeRecordDao;
	@Autowired
	SupplyCompeteRecordMmDao competeRecordMmDao;
	@Autowired
	SupplyCompeteDao supplyCompeteDao;

	/**
	 * 查看明细排名
	 * 
	 * @param inqId
	 * @return
	 */
	public HttpResult selectRankMmList(String inqId) {
		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("inqId", inqId);
		GridData gridData = new GridData();
		List<JSONObject> rows = new ArrayList<JSONObject>();
		List<ColumnsModel> columnsModels = new ArrayList<ColumnsModel>();
		List<ColumnsModel> froColumnsModels = new ArrayList<ColumnsModel>();
		ColumnsModel froColumnsModel = new ColumnsModel();
		froColumnsModel = new ColumnsModel();
		froColumnsModel.setField("mmCode");
		froColumnsModel.setTitle("物资编码");
		froColumnsModel.setWidth(100);
		froColumnsModels.add(froColumnsModel);
		froColumnsModel = new ColumnsModel();
		froColumnsModel.setField("mmDetail");
		froColumnsModel.setTitle("物资描述");
		froColumnsModels.add(froColumnsModel);
		froColumnsModel = new ColumnsModel();
		froColumnsModel.setField("planId");
		froColumnsModel.setTitle("planId");
		froColumnsModel.setHidden(true);
		froColumnsModels.add(froColumnsModel);

		List<PurchaseSupplyOffer> rankCompeteModels = supplyOfferMapper.selectSupplyOfferList(infoHashMap);
		for (PurchaseSupplyOffer purchaseSupplyOffer : rankCompeteModels) {
			ColumnsModel columnsModel = new ColumnsModel();
			columnsModel.setField(purchaseSupplyOffer.getInfId());
			columnsModel.setTitle(purchaseSupplyOffer.getInfName());
			columnsModel.setWidth(150);
			columnsModels.add(columnsModel);

			infoHashMap.put("infId", purchaseSupplyOffer.getInfId());
			List<PurchaseSupplyOfferMm> offerMms = supplyOfferMmMapper.selectAll(infoHashMap);
			if (purchaseSupplyOffer.equals(rankCompeteModels.get(0))) {
				for (PurchaseSupplyOfferMm offerMm : offerMms) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("planId", offerMm.getPlanId());
					jsonObject.put("mmCode", offerMm.getMmCode());
					jsonObject.put("mmDetail", offerMm.getMmDetail());
					jsonObject.put(offerMm.getInfId(), offerMm.getInqOfrUnitPrice());
					rows.add(jsonObject);
				}
			} else {
				// 使用stream流把list1和list2根据属性userId合并一个list集合
				rows = rows.stream().map(m -> {
					offerMms.stream().filter(m2 -> Objects.equals(m.get("planId"), m2.getPlanId())).forEach(m2 -> {
						m.put(m2.getInfId(), m2.getInqOfrUnitPrice());
					});
					return m;
				}).collect(Collectors.toList());
			}
		}

		gridData.setColumnsModels(columnsModels);
		gridData.setFroColumnsModels(froColumnsModels);
		gridData.setRows(rows);
		gridData.setTotal(rows.size());

		HttpResult httpResult = new HttpResult();
		httpResult.setData(gridData);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;

	}

	/**
	 * 报价揭示
	 *
	 * @param purchaseInquiryVO
	 * @return
	 */
	@Transactional
	public HttpResult revealInquiry(String inqId) {
		if (!StringUtils.isNotNull(inqId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqId);
		if (purchaseInquiry == null) {
			return HttpResult.error("询价书不存在！");
		}
		int result = 0;

		SysUser sysUser = SpringMvcUtils.getSysUser();
		purchaseInquiry.setInqActualTime(DateUtils.getCurrentTime());
		purchaseInquiry.setInqActualId(sysUser.getUserid());
		purchaseInquiry.setInqActualName(sysUser.getUsername());
		purchaseInquiry.setInqRevealStatus(Global.YES + "");

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("inqId", inqId);

		List<PurchaseSupplyOffer> rankCompeteModels = supplyOfferMapper.selectSupplyOfferList(infoHashMap);
		List<PurchaseSupplyOfferMm> rankCompeteMmModels = supplyOfferMmMapper.selectAll(infoHashMap);

		// 生成所有供应商总价排名，保存
		rankCompeteModels = rankCompeteModels.stream().filter(s -> s.getInqOfrTotalPrice() != null)
				.collect(Collectors.toList());
		rankCompeteModels = rankCompeteModels.stream().sorted(Comparator
				.comparing(PurchaseSupplyOffer::getInqOfrTotalPrice, Comparator.nullsLast(Comparator.naturalOrder())))
				.collect(Collectors.toList());
		int rank = 1;
		for (PurchaseSupplyOffer supplyCompeteModel : rankCompeteModels) {
			PurchaseSupplyOffer supplyOffer = new PurchaseSupplyOffer();
			supplyOffer.setInqId(inqId);
			supplyOffer.setInfId(supplyCompeteModel.getInfId());
			supplyOffer.setRank(rank++);
			supplyOfferMapper.update(supplyOffer);
		}

		// 所有供应商所有物资排序后，生成序号，返回本供应商
		rankCompeteMmModels = rankCompeteMmModels.stream().filter(s -> s.getInqOfrTotalPrice() != null)
				.collect(Collectors.toList());
		rankCompeteMmModels = rankCompeteMmModels.stream().filter(s -> s.getInqOfrTime() != null)
				.collect(Collectors.toList());
		rankCompeteMmModels = rankCompeteMmModels.stream()
				.sorted(Comparator.comparing(PurchaseSupplyOfferMm::getPlanId)
						.thenComparing(PurchaseSupplyOfferMm::getInqOfrUnitPrice,
								Comparator.nullsLast(Comparator.naturalOrder()))
						.thenComparing(PurchaseSupplyOfferMm::getInqOfrTime))
				.collect(Collectors.toList());

		int rankMm = 0;
		String planIdString = "";
		for (Iterator<PurchaseSupplyOfferMm> iteratorMm = rankCompeteMmModels.iterator(); iteratorMm.hasNext();) {
			PurchaseSupplyOfferMm supplyCompeteMmModel = (PurchaseSupplyOfferMm) iteratorMm.next();
			if (StringUtils.isNullOrEmpty(planIdString)) {
				planIdString = supplyCompeteMmModel.getPlanId();// 用第一条初始化
			}

			if (supplyCompeteMmModel.getPlanId().equals(planIdString)) {
				rankMm++;
			} else {// 当物资切换时
				planIdString = supplyCompeteMmModel.getPlanId();
				rankMm = 1;
			}

			PurchaseSupplyOfferMm supplyOfferMm = new PurchaseSupplyOfferMm();
			supplyOfferMm.setInqId(inqId);
			supplyOfferMm.setInfId(supplyCompeteMmModel.getInfId());
			supplyOfferMm.setPlanId(supplyCompeteMmModel.getPlanId());
			supplyOfferMm.setRank(rankMm);
			supplyOfferMmMapper.updateByPrimaryKey(supplyOfferMm);
		}

		result += inquiryMapper.update(purchaseInquiry);
		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setMsg("报价揭示成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("报价揭示失败！");
		}
		return httpResult;
	}

	@Autowired
	LogDao logDao;

	/**
	 * 撤回揭示
	 * 
	 * @param inqIdString
	 * @return
	 */
	@Transactional
	public HttpResult backReveal(String inqIdString) {
		if (!StringUtils.isNotNull(inqIdString)) {
			return HttpResult.error("参数不能为空");
		}

		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("inqId", inqIdString);
		List<PurchaseInquiryResult> inquiryResult = inquiryResultMapper.selectList(hashMap);

		if (inquiryResult != null && inquiryResult.size() > 0) {
			return HttpResult.error("请先删除询价结果!");
		}

		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqIdString);
		if (purchaseInquiry == null) {
			return HttpResult.error("询价书不存在！");
		}

		SysUser sysUser = SpringMvcUtils.getSysUser();
		purchaseInquiry.setInqActualTime("");
		purchaseInquiry.setInqActualId("");
		purchaseInquiry.setInqActualName("");
		purchaseInquiry.setInqRevealStatus(Global.NO + "");

		int result = 0;
		// 保存撤回日志
		result = inquiryMapper.update(purchaseInquiry);
		LogModel logModel = new LogModel();
		logModel.setLogId(UUID.randomUUID().toString());
		logModel.setLogContent(JSONObject.toJSONString(purchaseInquiry));
		logModel.setLogAction(ActionEnum.back.getName());
		logModel.setCreateTime(DateUtils.getCurrentTime());
		logDao.insert(logModel);

		HttpResult httpResult = new HttpResult();

		if (result > 0) {
			httpResult.setMsg("报价揭示回退成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("报价揭示回退失败！");
		}
		return httpResult;
	}

	/**
	 * 修改报价揭示时间
	 *
	 * @param purchaseInquiryVO
	 * @return
	 */
	@Transactional
	public HttpResult updateInquiryRevealTime(String inqIdString, String startTime, String endTime, String revealTime) {
		if (!StringUtils.isNotNull(inqIdString) || !StringUtils.isNotNull(startTime)
				|| !StringUtils.isNotNull(endTime)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqIdString);
		if (purchaseInquiry == null) {
			return HttpResult.error("询价书不存在！");
		} else if (purchaseInquiry.getInqRevealStatus().equals(Global.YES + "")) {
			return HttpResult.error("报价已揭示，不可修改！");
		}

		int result = 0;
		// 主表保存
		purchaseInquiry.setInqStartTime(startTime);
		purchaseInquiry.setInqEndTime(endTime);
		purchaseInquiry.setInqRevealTime(revealTime);
		result = inquiryMapper.update(purchaseInquiry);
		// 供应商报价表修改
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("inqId", inqIdString);
		List<PurchaseSupplyOffer> purchaseSupplyOffers = supplyOfferMapper.selectSupplyOfferList(hashMap);
		for (PurchaseSupplyOffer purchaseSupplyOffer : purchaseSupplyOffers) {
			purchaseSupplyOffer.setInqStartTime(startTime);
			purchaseSupplyOffer.setInqEndTime(endTime);
			supplyOfferMapper.update(purchaseSupplyOffer);
		}
		// 竞价表修改
		List<SupplyCompeteModel> supplyCompeteModels = supplyCompeteDao.selectByInqId(inqIdString);
		for (SupplyCompeteModel supplyCompeteModel : supplyCompeteModels) {
			supplyCompeteModel.setInqStartTime(startTime);
			supplyCompeteModel.setInqEndTime(endTime);
			supplyCompeteDao.update(supplyCompeteModel);
		}
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("保存成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}

	/**
	 * 修改竞价跟进时间
	 * 
	 * @param inqIdString
	 * @param endTime
	 * @return
	 */
	@Transactional
	public HttpResult updateLowStatus(String inqIdString, String endTime) {
		if (!StringUtils.isNotNull(inqIdString) || !StringUtils.isNotNull(endTime)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry purchaseInquiry = inquiryMapper.load(inqIdString);
		if (purchaseInquiry == null) {
			return HttpResult.error("询价书不存在！");
		} else if (!purchaseInquiry.getInqRevealStatus().equals(Global.YES + "")) {
			return HttpResult.error("报价非揭示状态，不可修改！");
		}

		int result = 0;
		purchaseInquiry.setInqEndTime(endTime);
		result += inquiryMapper.update(purchaseInquiry);
		// 供应商报价表修改
		List<SupplyCompeteModel> purchaseSupplyOffers = supplyCompeteDao.selectByInqId(inqIdString);
		for (SupplyCompeteModel purchaseSupplyOffer : purchaseSupplyOffers) {
			purchaseSupplyOffer.setLowStatus(Global.YES + "");
			purchaseSupplyOffer.setInqEndTime(endTime);
			result += supplyCompeteDao.update(purchaseSupplyOffer);
		}
		List<SupplyCompeteRecordModel> competeRecordModels = competeRecordDao.selectByInqId(inqIdString);
		for (SupplyCompeteRecordModel supplyCompeteRecordModel : competeRecordModels) {
			supplyCompeteRecordModel.setInqEndTime(endTime);
			result += competeRecordDao.update(supplyCompeteRecordModel);
		}

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("保存成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败！");
		}
		return httpResult;
	}
}
